package com.hu.system.service.impl;

import java.util.List;
import java.util.ArrayList;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hu.common.utils.SecurityUtils;
import com.hu.system.mapper.StockInboundMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.domain.StockInbound;
import com.hu.system.service.IStockInboundService;

/**
 * 库存入库Service业务层处理
 *
 * @author hu
 * @date 2025-01-21
 */
@Service
public class StockInboundServiceImpl implements IStockInboundService {
    @Autowired
    private StockInboundMapper stockInboundMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    /**
     * 查询库存入库列表
     *
     * @param stockInbound 库存入库
     * @return 库存入库
     */
    @Override
    public List<StockInbound> selectStockInboundList(StockInbound stockInbound) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部
        if (userId != null && userId == 1L) {
            return stockInboundMapper.selectStockInboundList(stockInbound);
        }

        // 普通用户根据店铺过滤
        // 清除分页参数，避免被店铺ID查询消耗
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || shopIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 设置店铺ID过滤条件（支持多店铺）
        stockInbound.getParams().put("shopIdList", shopIds);

        return stockInboundMapper.selectStockInboundList(stockInbound);
    }

    /**
     * 查询库存入库详细信息
     *
     * @param inboundId 库存入库ID
     * @return 库存入库
     */
    @Override
    public StockInbound selectStockInboundByInboundId(Long inboundId) {
        // 查询库存入库
        StockInbound inbound = stockInboundMapper.selectStockInboundList(new StockInbound() {{
            setInboundId(inboundId);
        }}).stream().findFirst().orElse(null);

        if (inbound == null) {
            return null;
        }

        Long userId = SecurityUtils.getUserId();

        // 管理员可以查看全部
        if (userId != null && userId == 1L) {
            return inbound;
        }

        // 普通用户需要验证店铺权限
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || !shopIds.contains(inbound.getShopId())) {
            return null; // 无权限
        }

        return inbound;
    }
}

